import { defineContentScript } from 'wxt/sandbox';
import { getAuthInfo, saveAuthInfo } from '../utils/erpapi';
import { COOKIE_NAMES, URL_CONFIG } from '../utils/defines';

console.log('Auth Content script is loading...');

// 获取 Cookie 值的辅助函数
function getCookie(name: string): string | null {
  const cookies = document.cookie.split(';');
  for (let cookie of cookies) {
    const [cookieName, cookieValue] = cookie.trim().split('=');
    if (cookieName === name) {
      return cookieValue;
    }
  }
  console.warn(`未找到 Cookie: ${name}`);
  return null;
}

// 检查并更新认证信息
async function checkAndUpdateAuth(): Promise<boolean> {
  console.log('开始检查认证信息...');
  console.log('当前所有 cookies:', document.cookie);

  const auth = getCookie(COOKIE_NAMES.AUTH_TOKEN);
  const ptoken = getCookie(COOKIE_NAMES.PROJECT_TOKEN);

  console.log('当前获取到的认证信息:', { auth, ptoken });

  if (auth && ptoken) {
    // 获取当前存储的认证信息进行对比
    const currentAuth = await getAuthInfo();
    console.log('当前存储的认证信息:', currentAuth);

    if (auth !== currentAuth.authorization || ptoken !== currentAuth.ptoken) {
      console.log('检测到认证信息变更，开始更新...');
      try {
        await saveAuthInfo(auth, ptoken);
        console.log('新的认证信息保存成功');

        // 验证保存的信息
        const savedInfo = await getAuthInfo();
        console.log('验证新保存的认证信息:', savedInfo);
        return true;
      } catch (error) {
        console.error('保存认证信息时出错:', error);
        return false;
      }
    } else {
      console.log('认证信息未发生变化，无需更新');
      return true;
    }
  } else {
    console.warn('未找到认证信息 Cookie');
    return false;
  }
}

// 创建认证状态提示
function createAuthStatusNotification(message: string, isSuccess = true): HTMLElement {
  // 检查是否已存在通知元素
  let notification = document.getElementById('kiki-auth-notification');
  if (!notification) {
    notification = document.createElement('div');
    notification.id = 'kiki-auth-notification';
    notification.style.position = 'fixed';
    notification.style.top = '20px';
    notification.style.right = '20px';
    notification.style.padding = '15px 20px';
    notification.style.borderRadius = '8px';
    notification.style.boxShadow = '0 4px 12px rgba(0, 0, 0, 0.15)';
    notification.style.zIndex = '9999';
    notification.style.fontSize = '14px';
    notification.style.fontWeight = 'bold';
    notification.style.transition = 'all 0.3s ease';
    document.body.appendChild(notification);
  }

  // 设置通知样式和内容
  notification.textContent = message;
  notification.style.backgroundColor = isSuccess ? '#4caf50' : '#ff5252';
  notification.style.color = 'white';

  // 显示通知
  notification.style.opacity = '1';
  notification.style.transform = 'translateY(0)';

  // 3秒后隐藏通知
  setTimeout(() => {
    notification.style.opacity = '0';
    notification.style.transform = 'translateY(-20px)';
    
    // 完全隐藏后移除元素
    setTimeout(() => {
      if (notification && notification.parentNode) {
        notification.parentNode.removeChild(notification);
      }
    }, 300);
  }, 3000);

  return notification;
}

// 检查认证状态并处理
async function handleAuthStatus() {
  // 检查当前是否在ERP网站
      const isErpSite = window.location.href.includes(URL_CONFIG.ERP_BASE_URL.replace('https://', ''));
  
  if (isErpSite) {
    // 如果在ERP网站，尝试获取认证信息
    const authSuccess = await checkAndUpdateAuth();
    
    if (authSuccess) {
      createAuthStatusNotification('认证信息已成功获取并保存', true);
    } else {
      // 如果在登录页面，不显示错误提示
      if (!window.location.href.includes('/login')) {
        createAuthStatusNotification('未能获取认证信息，请确保已登录', false);
      }
    }
  } else {
    // 如果不在ERP网站，检查是否有认证信息
    const authInfo = await getAuthInfo();
    
    if (!authInfo.authorization || !authInfo.ptoken) {
      // 如果没有认证信息，打开ERP网站
                  window.open(URL_CONFIG.ERP_BASE_URL + '/', '_blank');
      createAuthStatusNotification('正在打开ERP网站获取认证信息...', true);
    }
  }
}

export default defineContentScript({
  matches: ['<all_urls>'],
  main() {
    console.log('Auth content script loaded and running');
    
    // 页面加载完成后检查认证状态
    if (document.readyState === 'loading') {
      document.addEventListener('DOMContentLoaded', handleAuthStatus);
    } else {
      handleAuthStatus();
    }
    
    // 监听存储变化
    chrome.storage.onChanged.addListener((changes, namespace) => {
      if (namespace === 'local') {
        if (changes.kiki_auth || changes.kiki_ptoken) {
          console.log('检测到认证信息变化:', changes);
        }
      }
    });
    
    // 返回清理函数
    return () => {
      console.log('Auth content script unloading, cleaning up...');
    };
  },
});